import Vue from 'vue'
import Vuex from 'vuex'
import utils from '../util/util'
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import { Notification } from 'element-ui';

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
    state:{
        routes:[],
        sessions:{} ,
        admins:[],
        currentAdmin:JSON.parse(window.sessionStorage.getItem('user')),
        CurrentSession:null,
        filterKey:'',
        stomp:null,
        isDot:{}
    },
    getters:{

    },
    mutations:{
        INIT_ADMIN(state,data){
            state.currentAdmin = data;
        },
        initRoute(state,data){
            state.routes = data;
        },
        changeCurrentSession (state,currentSession) {
            state.CurrentSession = currentSession;
            Vue.set(state.isDot,state.currentAdmin.username +
                '#' + state.CurrentSession.username,false)
        },
        addMessage (state,msg) {
            let mss = state.sessions[state.currentAdmin.username+'#'+msg.to];
            if(!mss){
                // state.sessions[state.currentAdmin.username+'#'+msg.to] = [];
                Vue.set(state.sessions,state.currentAdmin.username+'#'+msg.to,[])
            }
            state.sessions[state.currentAdmin.username+'#'+msg.to].push({
                content:msg.content,
                date: new Date(),
                self: !msg.notSelf
            })
        },
        INIT_DATA (state) {
            //浏览器本地的历史聊天记录
            let data = null;
            utils.sendReq({
                queryUrl : 'chat/get',
                req:{
                    method:'post',
                    success:function(req){
                        if (req.data.code == 200){
                            data = req.data.msg;
                            if (data) {
                                state.sessions = JSON.parse(data);
                            }
                        }
                    }
                }
            })
            // let data = localStorage.getItem('vue-chat-session');
            //console.log(data)
        },
        INIT_ADMINS(state,data){
            state.admins = data;
        },
    },
    actions:{
        connect(context){
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            let token  = window.sessionStorage.getItem('token');
            context.state.stomp.connect({'Auth-Token':token},success=>{
                context.state.stomp.subscribe('/user/queue/chat',msg=>{
                    let receiveMsg = JSON.parse(msg.body);

                    if (!context.state.CurrentSession ||
                        receiveMsg.from != context.state.CurrentSession.username){
                        Notification.info({
                            title:'【'+receiveMsg.formNickName + '】发来一条消息',
                            message:receiveMsg.content.length > 10
                                ? receiveMsg.content.substring(0,10) + "..."
                                :receiveMsg.content
                        });
                        Vue.set(context.state.isDot,context.state.currentAdmin.username +
                        '#' + receiveMsg.from,true)
                    }
                    receiveMsg.notSelf = true;
                    receiveMsg.to = receiveMsg.from;
                    context.commit('addMessage',receiveMsg);
                })
            },error=>{
                console.log('error====>');
            });
        },
        initData (context) {
            context.commit('INIT_DATA');
            // utils.sendReq({
            //     queryUrl:"/chat/admin",
            //     req:{
            //         method:"get",
            //         success:function(req){
            //             if (req.data.code === 200){
            //                 context.commit('INIT_ADMINS',req.data.data)
            //             }
            //         }
            //     }
            // })
        }
    }
})


store.watch(function (state) {
    return state.sessions
},function (val) {
    console.log('CHANGE: ', val);
    // localStorage.setItem('vue-chat-session', JSON.stringify(val));
    utils.sendReq({
        queryUrl : 'chat/set',
        req:{
            data:JSON.stringify(val),
            method:'post',
            success:function(){

            }
        }
    })
},{
    deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;
